package com.example.demo.controller;

import com.example.demo.account.AccountInfo;
import com.example.demo.common.BaseResponse;
import com.example.demo.common.ErrorCode;
import com.example.demo.common.ResultUtils;
import com.example.demo.exception.BusinessException;
import com.example.demo.service.AccountService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 账户信息
 * @author Atanycosts
 */
@RestController
@RequestMapping("/api/account")
@CrossOrigin(origins = "*")
public class AccountController {

    private static final Logger log = LoggerFactory.getLogger(AccountController.class);

    @Autowired
    private AccountService accountService;

    /**
     * 创建新账户
     */
    @PostMapping("/create")
    public BaseResponse<AccountInfo> createAccount() {
        try {
            AccountInfo accountInfo = accountService.createAccount();
            return ResultUtils.success(accountInfo);
        } catch (Exception e) {
            log.error("创建账户失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "创建账户失败：" + e.getMessage());
        }
    }

    /**
     * 从私钥加载账户
     */
    @PostMapping("/load")
    public BaseResponse<AccountInfo> loadAccount(@RequestParam String privateKey) {
        if (privateKey == null || privateKey.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "私钥不能为空");
        }
        
        try {
            AccountInfo accountInfo = accountService.loadAccountFromPrivateKey(privateKey);
            return ResultUtils.success(accountInfo);
        } catch (Exception e) {
            log.error("加载账户失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "加载账户失败：" + e.getMessage());
        }
    }

    /**
     * 获取账户信息
     */
    @GetMapping("/{address}")
    public BaseResponse<AccountInfo> getAccount(@PathVariable String address) {
        if (address == null || address.isEmpty()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "地址不能为空");
        }
        
        try {
            AccountInfo accountInfo = accountService.getAccount(address);
            return ResultUtils.success(accountInfo);
        } catch (Exception e) {
            log.error("获取账户信息失败", e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "获取账户信息失败：" + e.getMessage());
        }
    }
}